<template>
  <div class="p-6 bg-gray-50 dark:bg-gray-900">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold dark:text-white">房间管理</h2>
      <div class="flex space-x-4">
        <a-button type="primary" @click="showCreateRoom = true">
          <template #icon><icon-plus /></template>
          添加房间
        </a-button>
        <a-button type="outline" @click="exportRooms">
          <template #icon><icon-download /></template>
          导出数据
        </a-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
      <a-form :model="searchForm" layout="inline">
        <a-form-item field="roomNumber" label="房间号">
          <a-input
            v-model="searchForm.roomNumber"
            placeholder="请输入房间号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="roomType" label="房型">
          <a-select
            v-model="searchForm.roomType"
            placeholder="请选择房型"
            allow-clear
            style="width: 200px"
          >
            <a-option value="single">标准单人房</a-option>
            <a-option value="double">标准双人房</a-option>
            <a-option value="deluxe">豪华大床房</a-option>
            <a-option value="suite">豪华套房</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 200px"
          >
            <a-option value="available">空闲</a-option>
            <a-option value="occupied">已入住</a-option>
            <a-option value="maintenance">维护中</a-option>
            <a-option value="reserved">已预订</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="searchRooms">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="resetSearch">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <!-- 房间列表 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow">
      <a-table
        :data="rooms"
        :columns="columns"
        :pagination="pagination"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <!-- 房型列 -->
        <template #roomType="{ record }">
          <div class="flex items-center">
            <a-image
              :src="record.image"
              :alt="record.roomType"
              width="60"
              height="40"
              fit="cover"
              class="rounded"
            />
            <span class="ml-2">{{ getRoomTypeName(record.roomType) }}</span>
          </div>
        </template>

        <!-- 价格列 -->
        <template #price="{ record }">
          <div>
            <div class="text-red-500 dark:text-red-400">
              ¥{{ record.price }}
            </div>
            <div
              class="text-gray-400 dark:text-gray-500 text-sm line-through"
              v-if="record.originalPrice"
            >
              ¥{{ record.originalPrice }}
            </div>
          </div>
        </template>

        <!-- 状态列 -->
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>

        <!-- 操作列 -->
        <template #operation="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="editRoom(record)">
              编辑
            </a-button>
            <a-button type="text" size="small" @click="viewRoomDetails(record)">
              查看
            </a-button>
            <a-popconfirm
              content="确定要删除该房间吗？"
              @ok="deleteRoom(record)"
            >
              <a-button type="text" status="danger" size="small">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑房间弹窗 -->
    <a-modal
      v-model:visible="showCreateRoom"
      :title="editingRoom ? '编辑房间' : '添加房间'"
      @cancel="cancelEdit"
      @before-ok="handleSubmit"
    >
      <a-form ref="roomForm" :model="roomForm" layout="vertical">
        <a-form-item field="roomNumber" label="房间号" required>
          <a-input
            v-model="roomForm.roomNumber"
            placeholder="请输入房间号"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="roomType" label="房型" required>
          <a-select
            v-model="roomForm.roomType"
            placeholder="请选择房型"
            style="width: 100%"
          >
            <a-option value="single">标准单人房</a-option>
            <a-option value="double">标准双人房</a-option>
            <a-option value="deluxe">豪华大床房</a-option>
            <a-option value="suite">豪华套房</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="floor" label="楼层" required>
          <a-input-number
            v-model="roomForm.floor"
            placeholder="请输入楼层"
            style="width: 100%"
            :min="1"
            :max="99"
          />
        </a-form-item>
        <a-form-item field="price" label="价格" required>
          <a-input-number
            v-model="roomForm.price"
            placeholder="请输入价格"
            style="width: 100%"
            :min="0"
            :precision="2"
          />
        </a-form-item>
        <a-form-item field="originalPrice" label="原价">
          <a-input-number
            v-model="roomForm.originalPrice"
            placeholder="请输入原价"
            style="width: 100%"
            :min="0"
            :precision="2"
          />
        </a-form-item>
        <a-form-item field="status" label="状态" required>
          <a-select
            v-model="roomForm.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <a-option value="available">空闲</a-option>
            <a-option value="maintenance">维护中</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="description" label="房间描述">
          <a-textarea
            v-model="roomForm.description"
            placeholder="请输入房间描述"
            :max-length="500"
            show-word-limit
            allow-clear
          />
        </a-form-item>
        <a-form-item field="image" label="房间图片">
          <a-upload
            list-type="picture-card"
            :action="'/api/upload'"
            :limit="1"
            @before-upload="beforeUpload"
            @success="onUploadSuccess"
          >
            <template #upload-button>
              <div class="flex flex-col items-center">
                <icon-upload />
                <div class="mt-2">上传图片</div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 房间详情弹窗 -->
    <a-modal
      v-model:visible="showRoomDetails"
      title="房间详情"
      @cancel="closeRoomDetails"
      :footer="false"
      width="800px"
    >
      <div v-if="selectedRoom" class="space-y-6">
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >房间号</label
            >
            <div class="mt-1 dark:text-gray-200">
              {{ selectedRoom.roomNumber }}
            </div>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >房型</label
            >
            <div class="mt-1 dark:text-gray-200">
              {{ getRoomTypeName(selectedRoom.roomType) }}
            </div>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >楼层</label
            >
            <div class="mt-1 dark:text-gray-200">
              {{ selectedRoom.floor }}层
            </div>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >价格</label
            >
            <div class="mt-1 dark:text-gray-200">¥{{ selectedRoom.price }}</div>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >状态</label
            >
            <div class="mt-1 dark:text-gray-200">
              <a-tag :color="getStatusColor(selectedRoom.status)">
                {{ getStatusText(selectedRoom.status) }}
              </a-tag>
            </div>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300"
              >最近预订</label
            >
            <div class="mt-1 dark:text-gray-200">
              {{ selectedRoom.lastBooking || "无" }}
            </div>
          </div>
        </div>
        <div>
          <label
            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >房间描述</label
          >
          <div class="mt-1 dark:text-gray-200">
            {{ selectedRoom.description || "无" }}
          </div>
        </div>
        <div>
          <label
            class="block text-sm font-medium text-gray-700 dark:text-gray-300"
            >房间图片</label
          >
          <div class="mt-1">
            <a-image
              :src="selectedRoom.image"
              :alt="selectedRoom.roomNumber"
              width="100%"
              height="300"
              fit="cover"
              class="rounded"
            />
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconPlus,
  IconDownload,
  IconSearch,
  IconRefresh,
  IconUpload,
} from "@arco-design/web-vue/es/icon";

// 搜索表单
const searchForm = reactive({
  roomNumber: "",
  roomType: "",
  status: "",
});

// 房间表单
const roomForm = reactive({
  roomNumber: "",
  roomType: "",
  floor: 1,
  price: 0,
  originalPrice: 0,
  status: "available",
  description: "",
  image: "",
});

// 表格列配置
const columns = [
  {
    title: "房间号",
    dataIndex: "roomNumber",
  },
  {
    title: "房型",
    slotName: "roomType",
  },
  {
    title: "楼层",
    dataIndex: "floor",
    render: ({ record }) => `${record.floor}层`,
  },
  {
    title: "价格",
    slotName: "price",
  },
  {
    title: "状态",
    slotName: "status",
  },
  {
    title: "最近预订",
    dataIndex: "lastBooking",
  },
  {
    title: "操作",
    slotName: "operation",
    width: 160,
  },
];

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
});

// 模拟房间数据
const rooms = ref([
  {
    id: 1,
    roomNumber: "801",
    roomType: "deluxe",
    floor: 8,
    price: 688,
    originalPrice: 888,
    status: "available",
    lastBooking: "2024-02-25",
    description: "豪华大床房，面积35平米，大床2x2米，有浴缸",
    image: "/room-1.jpg",
  },
  {
    id: 2,
    roomNumber: "802",
    roomType: "double",
    floor: 8,
    price: 488,
    originalPrice: 588,
    status: "occupied",
    lastBooking: "2024-02-26",
    description: "标准双人房，面积30平米，双床1.2x2米",
    image: "/room-2.jpg",
  },
]);

// 控制弹窗显示
const showCreateRoom = ref(false);
const showRoomDetails = ref(false);
const selectedRoom = ref(null);
const editingRoom = ref(null);

// 获取房型名称
const getRoomTypeName = (type) => {
  const types = {
    single: "标准单人房",
    double: "标准双人房",
    deluxe: "豪华大床房",
    suite: "豪华套房",
  };
  return types[type] || type;
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colors = {
    available: "green",
    occupied: "blue",
    maintenance: "orange",
    reserved: "purple",
  };
  return colors[status] || "gray";
};

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    available: "空闲",
    occupied: "已入住",
    maintenance: "维护中",
    reserved: "已预订",
  };
  return texts[status] || status;
};

// 搜索房间
const searchRooms = () => {
  // 调用API搜索房间
  Message.success("搜索成功");
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchRooms();
};

// 导出数据
const exportRooms = () => {
  Message.success("导出成功");
};

// 编辑房间
const editRoom = (room) => {
  editingRoom.value = room;
  Object.keys(roomForm).forEach((key) => {
    roomForm[key] = room[key];
  });
  showCreateRoom.value = true;
};

// 查看房间详情
const viewRoomDetails = (room) => {
  selectedRoom.value = room;
  showRoomDetails.value = true;
};

// 关闭房间详情
const closeRoomDetails = () => {
  showRoomDetails.value = false;
  selectedRoom.value = null;
};

// 删除房间
const deleteRoom = async (room) => {
  try {
    // 调用API删除房间
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("删除成功");
    // 重新加载房间列表
    searchRooms();
  } catch (error) {
    Message.error("删除失败");
  }
};

// 取消编辑
const cancelEdit = () => {
  editingRoom.value = null;
  Object.keys(roomForm).forEach((key) => {
    roomForm[key] = "";
  });
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 调用API保存房间信息
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success(editingRoom.value ? "修改成功" : "添加成功");
    showCreateRoom.value = false;
    cancelEdit();
    // 重新加载房间列表
    searchRooms();
    return true;
  } catch (error) {
    Message.error(editingRoom.value ? "修改失败" : "添加失败");
    return false;
  }
};

// 图片上传前校验
const beforeUpload = (file) => {
  const isImage = /^image\//.test(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    Message.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    Message.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

// 图片上传成功
const onUploadSuccess = (response) => {
  roomForm.image = response.url;
  Message.success("上传成功");
};

// 分页相关方法
const onPageChange = (current) => {
  pagination.current = current;
  searchRooms();
};

const onPageSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  searchRooms();
};
</script>
